import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getProjectList, type Project, type ProjectListParams } from '@/api/project'

export const useProjectStore = defineStore('project', () => {
  const projects = ref<Project[]>([])
  const currentProject = ref<Project | null>(null)
  const loading = ref(false)

  // 获取项目列表
  const fetchProjects = async (params: ProjectListParams) => {
    loading.value = true
    try {
      const response = await getProjectList(params)
      projects.value = response.items
      return { success: true, data: response }
    } catch (error: any) {
      return { success: false, message: error.message || '获取项目列表失败' }
    } finally {
      loading.value = false
    }
  }

  // 设置当前项目
  const setCurrentProject = (project: Project | null) => {
    currentProject.value = project
  }

  // 添加项目到列表
  const addProject = (project: Project) => {
    projects.value.unshift(project)
  }

  // 更新项目
  const updateProject = (project: Project) => {
    const index = projects.value.findIndex(p => p.id === project.id)
    if (index !== -1) {
      projects.value[index] = project
    }
    if (currentProject.value?.id === project.id) {
      currentProject.value = project
    }
  }

  // 删除项目
  const removeProject = (projectId: number) => {
    projects.value = projects.value.filter(p => p.id !== projectId)
    if (currentProject.value?.id === projectId) {
      currentProject.value = null
    }
  }

  return {
    projects,
    currentProject,
    loading,
    fetchProjects,
    setCurrentProject,
    addProject,
    updateProject,
    removeProject
  }
})


